package com.elite.groovy.callback

import cn.com.callback.PageInfo
import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.security.MessageDigest
import java.text.SimpleDateFormat

class RobotListImports implements ServiceBackInvoke {

	private static final Log log=LogFactory.getLog(RobotListImports.class);
	@Override
	public String doCallBack(EliteBean elite, HttpServletRequest request,HttpServletResponse response) {
		log.debug("开始启动青牛智能机器人拨打首拨名单下发");
		JSONObject js = new JSONObject();
		JSONObject objtwo = null;
		long startTime=System.currentTimeMillis();
		String taskNames="";
		String tasks="";
		int count = 0;
		int count1 = 0;
		JSONArray arr3 = new JSONArray();
		try {
			//获取配置文件中配置好的企业号、代理ip及端口
			PropertiesUtil cfg = new PropertiesUtil();
			def Te_entId = cfg.readValue("QingNiu.EntId");
			Date date=new Date();
			//当前系统时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			//活动批次号的拼接字符
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
			//获得当前系统时间字符串
			String dates=sdf.format(date);
			String date1=sdf2.format(date);
			log.debug("date"+date);
			log.debug("date1"+date1);
			//获得企业id
			def enterpriseID = cfg.readValue("QingNiu.enterpriseID");
			def salt = "8127cc9b6adfd49946bf07140d301f6c";
			StringBuffer s = new StringBuffer();
			s.append(enterpriseID);
			s.append(dates);
			s.append(salt);
			String ss = s.toString();
			def tk = MD5(ss);
			//字符转大写
			def token = tk.toUpperCase();
			String proxyIp = cfg.readValue("QingNiu.ProxyIP");
			int proxyPort=0;
			if(cfg.readValue("QingNiu.ProxyPort")!=null&&cfg.readValue("QingNiu.ProxyPort")!="") {
				proxyPort = cfg.readValue("QingNiu.ProxyPort").toInteger();
			}
			def id=getRandomString(32);

			//判断今天下发的运行中的活动是否到了活动截止时间
			String sql1 = "select  CUSTLIST_NAME from robot_standard_rule  where  TASK_END_DATE<=trunc(sysdate)";
			List s1=elite.chaxun_sql(sql1, "dataSource");
			log.debug("查询sql1:"+sql1);
			JSONArray jsonArray1=JSONArray.fromObject(s1);
			int ListNum1 = jsonArray1.size();
			JSONObject json3 = null;
			if(ListNum1>0){
				for(int i = 0; i<ListNum1; i++) {
					json3 = jsonArray1.getJSONObject(i);
					//获取到了时间的活动名称并删除相关活动以及临时表名单
					def cuslistName1 = GetJV(json3, "CUSTLIST_NAME");
					String deletesql1="delete   from robot_standard_rule where CUSTLIST_NAME='"+cuslistName1+"' ";
					elite.update(deletesql1, "dataSource");
					String deletesql2="delete from robot_push_temporary where  CUSTLIST='"+cuslistName1+"' ";
					elite.update(deletesql2, "dataSource");
				}
			}
			//判断今天下发的运行中的活动是否满足节假日下发规则
			String sql2 = "select CREATEDGROUP from c_freedate  where FREEDATE=trunc(sysdate)";
			log.debug("查询sql2:"+sql2);
			List s2=elite.chaxun_sql(sql2, "dataSource");
			JSONArray jsonArray2=JSONArray.fromObject(s2);
			int ListNum2 = jsonArray2.size();
			if(ListNum2>0){
			    String sql8 = "update ROBOT_STANDARD_RULE set TASK_STATUS = 2,STARTTIME1=STARTTIME1+1,ENDTIME1=ENDTIME1+1,STARTTIME2=STARTTIME2+1,ENDTIME2=ENDTIME2+1 where TASK_START_DATE<=trunc(sysdate) and TASK_STATUS = 1 and freeday=0 and createdgroup in (select createdgroup from c_freedate where freedate=trunc(sysdate)  )";
				elite.update(sql8, "dataSource");
				//活动是启用中的并且下发时间在当前时间之后的节假日不允许下发的且不在节假日中的活动状态更改为运行中
				String sql3 = "update ROBOT_STANDARD_RULE set TASK_STATUS = 2 where TASK_START_DATE<=trunc(sysdate) and TASK_STATUS = 1 and freeday=0 and createdgroup not in (select createdgroup from c_freedate where freedate=trunc(sysdate)  )";
				elite.update(sql3, "dataSource");
				log.debug("查询sql3:"+sql3);
				//活动是启用中的并且下发时间在当前时间之后的节假日允许下发的活动状态更改为运行中
				String sql4 = "update ROBOT_STANDARD_RULE set TASK_STATUS = 2 where TASK_START_DATE<=trunc(sysdate) and TASK_STATUS = 1 and freeday=1";
				elite.update(sql4, "dataSource");
				log.debug("查询sql4:"+sql4);
				//查询出可下发的运行中的活动明细数据
				String selectsql1="select distinct daily_quantity_issued,repeattimes,advance,intervals,process_id,businesssendcid,calller,case when starttime1 is null then to_date('2000-01-01','yyyy-mm-dd') else starttime1 end starttime1,case when endtime1 is null then to_date('2000-01-01','yyyy-mm-dd') else endtime1 end endtime1,case when starttime2 is null then to_date('2000-01-01','yyyy-mm-dd') else starttime2 end starttime2,case when endtime2 is null then to_date('2000-01-01','yyyy-mm-dd') else endtime2 end endtime2,task_ruleid,lavenum,createdgroup,blacklist,SKILL_GROUP from robot_standard_rule where TASK_START_DATE <= trunc(sysdate+1) and TASK_END_DATE > trunc(sysdate) and TASK_STATUS ='2'  and freeday=1 union all select distinct daily_quantity_issued,repeattimes,advance,intervals,process_id,businesssendcid,calller,case when starttime1 is null then to_date('2000-01-01','yyyy-mm-dd') else starttime1 end starttime1,case when endtime1 is null then to_date('2000-01-01','yyyy-mm-dd') else endtime1 end endtime1,case when starttime2 is null then to_date('2000-01-01','yyyy-mm-dd') else starttime2 end starttime2,case when endtime2 is null then to_date('2000-01-01','yyyy-mm-dd') else endtime2 end endtime2,task_ruleid,lavenum,createdgroup,blacklist,SKILL_GROUP from robot_standard_rule where TASK_START_DATE <= trunc(sysdate+1)  and TASK_END_DATE > trunc(sysdate) and TASK_STATUS = '2' and freeday=0   and CREATEDGROUP not in ( select CREATEDGROUP from c_freedate  where FREEDATE=trunc(sysdate) )";
				List rs = elite.chaxun_sql(selectsql1, "dataSource");
				log.debug("查询selectsql1:"+selectsql1);
				arr3=JSONArray.fromObject(rs);
				int ListNum = arr3.size();
				log.debug("查询ListNum:"+ListNum);
				count = ListNum;
			}else{
				//活动是启用中的并且下发时间在当前时间之后的活动状态更改为运行中
				String sql5 = "update ROBOT_STANDARD_RULE set TASK_STATUS = 2 where TASK_START_DATE<=trunc(sysdate) and TASK_STATUS = 1";
				elite.update(sql5, "dataSource");
				//查询出可下发的运行中的活动明细数据
				String selectsql1="select distinct daily_quantity_issued,repeattimes,advance,intervals,process_id,businesssendcid,calller,case when starttime1 is null then to_date('2000-01-01','yyyy-mm-dd') else starttime1 end starttime1,case when endtime1 is null then to_date('2000-01-01','yyyy-mm-dd') else endtime1 end endtime1,case when starttime2 is null then to_date('2000-01-01','yyyy-mm-dd') else starttime2 end starttime2,case when endtime2 is null then to_date('2000-01-01','yyyy-mm-dd') else endtime2 end endtime2,task_ruleid,lavenum,createdgroup,blacklist,SKILL_GROUP from robot_standard_rule where TASK_START_DATE <= trunc(sysdate+1) and TASK_END_DATE > trunc(sysdate) and TASK_STATUS ='2'";
				List rs = elite.chaxun_sql(selectsql1, "dataSource");
				arr3=JSONArray.fromObject(rs);
				int ListNum = arr3.size();
				log.debug("查询ListNum:"+ListNum);
				count = ListNum;
			}
			log.debug("查询count:"+count);
			if(count>0) {
				//名单导入接口地址
				String qnUrl = "select webserviceurl from Sysc_Interface where webtype ='UPLOADCALLDATA'";
				def postURL=elite.chaxun_sql(qnUrl, "dataSource");
				def url=postURL[0].get("WEBSERVICEURL");
				//活动任务推送地址
				String qnUrl1 = "select webserviceurl from Sysc_Interface where webtype ='STATCALL'";
				def postURL1=elite.chaxun_sql(qnUrl1, "dataSource");
				def url1=postURL1[0].get("WEBSERVICEURL");
				JSONObject json = null;
				for(int i = 0; i<count; i++) {
					JSONArray array = new JSONArray();
					json = arr3.getJSONObject(i);
					log.debug("json:"+json);
					//获取批次即requestId
					def requestId = GetJV(json, "TASK_RULEID");
					def blacklist = GetJV(json, "BLACKLIST");
					def skill_group = GetJV(json, "SKILL_GROUP");
					JSONObject timeRange = new JSONObject();
					def start1 = GetJV(json, "STARTTIME1");
					JSONObject jsonObject1 = new JSONObject().fromObject(start1);
					String startTime11 = GetJV(jsonObject1, "time");
					def end1 = GetJV(json, "ENDTIME1");
					JSONObject jsonObject2 = new JSONObject().fromObject(end1);
					String endTime11 = GetJV(jsonObject2, "time");
					if(startTime11!=endTime11){
						String result1=timeStampDate(startTime11);
						String result2=timeStampDate(endTime11);
						timeRange.put("startTime", result1);
						timeRange.put("endTime", result2);
						array.add(timeRange);
					}
					JSONObject timeRange1 = new JSONObject();
					def start2 = GetJV(json, "STARTTIME2");
					JSONObject jsonObject3 = new JSONObject().fromObject(start2);
					String startTime21 = GetJV(jsonObject3, "time");
					def end2 = GetJV(json, "ENDTIME2");
					JSONObject jsonObject4 = new JSONObject().fromObject(end2);
					String endTime21 = GetJV(jsonObject4, "time");
					log.debug("startTime21:" + startTime21);
					log.debug("endTime21:" + endTime21);
					if(startTime21!=endTime21){
						String result3=timeStampDate(startTime21);
						String result4=timeStampDate(endTime21);
						timeRange1.put("startTime", result3);
						timeRange1.put("endTime", result4);
						array.add(timeRange1);
					}
					log.debug("array:"+array);
					String caller = GetJV(json, "CALLLER");
					String repeatTimes = GetJV(json, "REPEATTIMES");
					String processId = GetJV(json, "PROCESS_ID");
					String spanSec = GetJV(json, "INTERVALS");
					String businessSendcId = GetJV(json, "BUSINESSSENDCID");
					JSONObject json1 = new JSONObject();
					json1.put("enterpriseID", enterpriseID);
					//json1.put("requestId", requestId1);
					json1.put("timeRange",array);
					json1.put("caller",caller);
					json1.put("repeatTimes",repeatTimes);
					json1.put("processId",processId);
					json1.put("spanSec",spanSec);
					json1.put("businessSendcId",businessSendcId);
					json1.put("token",token);
					//获取每日下发量
					String sql6="";
					String sql7="";
					//def dailyQuantityIssued = String.valueOf(GetJV(json, "DAILY_QUANTITY_ISSUED"));
					Integer dailyQuantityIssued = 0;
					dailyQuantityIssued = Integer.parseInt(String.valueOf(GetJV(json, "DAILY_QUANTITY_ISSUED")));
					log.debug("dailyQuantityIssued:"+dailyQuantityIssued);
					//Integer dailyQuantityIssued = GetJV(json, "DAILY_QUANTITY_ISSUED");
					if(dailyQuantityIssued>0){
						sql7=" and rownum<="+dailyQuantityIssued+"";
					}
					//获取保险到期日提前下发天数
					def advance = GetJV(json, "ADVANCE");
					if(advance=='1'){
						sql6=" and (in_enddate_new - trunc(sysdate)) =45";
					}
					else if(advance=='2'){
						sql6=" and (in_enddate_new - trunc(sysdate)) <=45 and (in_enddate_new - trunc(sysdate)) >=0";
					}
					else if(advance=='3'){
						sql6=" and (in_enddate_new - trunc(sysdate)) =30";
					}
					else if(advance=='4'){
						sql6=" and (in_enddate_new - trunc(sysdate)) <=30 and (in_enddate_new - trunc(sysdate)) >=0";
					}else if(advance=='5'){
						sql6=" and (in_enddate_new - trunc(sysdate)) =365";
					}
					String setFlag = "";

					Integer setFlagRow = 0;

					//根据批次号到期日以及每日下发数量查询出临时表中对应批次的每日下发名单数量
					setFlag="update robot_push_temporary set is_push = 2, ordernumber = rownum where customer_guid in (select * from ( (select customer_guid  from robot_push_temporary  where custlist in (select custlist_name from robot_standard_rule  where task_ruleid = '"+requestId+"') and is_push = 1  "+sql6+" "+sql7+" order by in_enddate desc)))";
					log.debug("推送总数量SQL：" + setFlag.toString());
					setFlagRow = elite.update(setFlag.toString(), "dataSource");
					log.debug(requestId+"推送总数量：" + setFlagRow);
					if(setFlagRow>0){
						//页码
						int pageNo = 0;
						int pageNo1= 0;
						//每页显示的数据
						int pageSize = 2000;
						//总数据
						int totalNum = setFlagRow;
						//总页
						int totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : (totalNum / pageSize)+1;
						log.debug("推送总页数：" + totalPage);
						PageInfo page = new PageInfo();
						page.setPageSize(pageSize);
						page.setTotalNum(totalNum);
						page.setTotalPage(totalPage);
						//分页推送(每页推送数据不得超过2000条)
						for(int k = 0; k < totalPage; k++) {
							pageNo = pageNo+1;
							pageNo1=pageNo-1;
							String selectsql2="SELECT * FROM (select customer_guid custId, robot_activity_name CALLLISTNAME,  customer_name CUSTOMERNAME, mobile,tel_1, atel_1,atel_2,atel_3,atel_4,objective_guid,caller,sex, car_plate, IN_ENDDATE_NEW,ordernumber from robot_push_temporary where custlist in (select custlist_name from robot_standard_rule where  task_ruleid= '"+requestId+"') and Is_push = '2' and ordernumber <= "+pageNo*pageSize+" ) tt WHERE tt.ordernumber >  "+pageNo1*pageSize+"";
							List result = elite.chaxun_sql(selectsql2,"dataSource");
							JSONArray jsons = JSONArray.fromObject(result);
							int listNums = jsons.size();
							JSONArray arr = new JSONArray();
							JSONArray arr1 = new JSONArray();
							JSONObject obj = new JSONObject();
							JSONObject obj1 = new JSONObject();
							for(int j = 0; j<listNums; j++) {
								JSONObject userJson = new JSONObject();
								JSONObject dataObject = jsons.getJSONObject(j);
								def cust_id=GetJV(dataObject, "CUSTID");
								def taskName = GetJV(dataObject, "CALLLISTNAME");
								taskNames = taskName+getRandomString(8);
								def customerName=GetJV(dataObject, "CUSTOMERNAME");
								//log.debug("customerName:" + customerName);
								//String names = URLEncoder.encode(customerName, "UTf-8");
								def objectiveGuid = GetJV(dataObject, "OBJECTIVE_GUID");
								def phoneNumber1 = GetJV(dataObject, "MOBILE");
								def phoneNumber2 = GetJV(dataObject, "TEL_1");
								def phoneNumber3 = GetJV(dataObject, "ATEL_1");
								def phoneNumber4 = GetJV(dataObject, "ATEL_2");
								def phoneNumber5 = GetJV(dataObject, "ATEL_3");
								def phoneNumber6 = GetJV(dataObject, "ATEL_4");
								def caller1 = GetJV(dataObject, "CALLER");
								def carPlate = GetJV(dataObject, "CAR_PLATE");
								//log.debug("dataObject:" + dataObject);
								def in_enddate = GetJV(dataObject, "IN_ENDDATE_NEW");
								//log.debug("in_enddate:" + in_enddate);
								JSONObject jsonObject5 = new JSONObject().fromObject(in_enddate);
								String inEndDate = timeStampDate(GetJV(jsonObject5, "time"));
								userJson.put("skill", skill_group);
								userJson.put("carPlate", carPlate);
								userJson.put("inEndDate", inEndDate);
								obj.put("custId", cust_id+"#"+objectiveGuid);
								obj.put("username",  customerName);
								obj.put("caller",  caller1);
								obj.put("phoneNum5", phoneNumber5);
								obj.put("phoneNum1", phoneNumber1);
								obj.put("phoneNum2", phoneNumber2);
								obj.put("phoneNum3", phoneNumber3);
								obj.put("phoneNum4", phoneNumber4);
								obj.put("phoneNum5", phoneNumber5);
								obj.put("userData", userJson);
								arr.add(obj);
							}
							objtwo = new JSONObject();
							def requestId1= requestId+getRandomString(8);
							json1.put("requestId", requestId1);
							objtwo.put("requestId", requestId1);
							objtwo.put("enterpriseID", enterpriseID);
							objtwo.put("addType","2");
							objtwo.put("taskName",taskNames);
							objtwo.put("token",token);
							objtwo.put("coverType","0");
							objtwo.put("blackList",blacklist);
							objtwo.put("jsonData", arr);
							log.debug("调用青牛语音平台请求报文:" + objtwo.toString());

							def reJson1 = HttpClientProxy.sendPost(url, objtwo.toString(),proxyIp,proxyPort);
							JSONObject j = new JSONObject().fromObject(reJson1);
							long etime=System.currentTimeMillis();

							//定义推送标记
							String code = j.code;
							//记录日志
							//String I_Sync_Type="ROBOT2";
							//def insertSQL="DECLARE  clobValue qt_dm_ifc_log_new.Send_Info%TYPE; clobValue1 //qt_dm_ifc_log_new.return_info%TYPE;  BEGIN  clobValue:='' ; clobValue1:='" + reJson + "';insert into //qt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'" + //requestId + "','" + I_Sync_Type + "',clobValue,clobValue1,sysdate,sysdate);   COMMIT; END;";
							//elite.update(insertSQL,'dataSource');
							log.debug("本次推送名单是否成功code："+code);
							if(code.equals("0") || code == "0") {
								//记录本次推送历史
								String addHistory = "insert into robot_push_history (id,customer_guid,customer_name, robot_activity_name, custlist, createddate,tel_1,mobile,atel_1,atel_2,atel_3,atel_4,is_push,in_enddate,IN_ENDDATE_NEW,createdby,objective_guid, send_type,caller, temp_id,listrank,release_date, release_status, sex, car_plate, modifieddate) select id,customer_guid,customer_name, robot_activity_name,custlist,sysdate,tel_1,mobile,atel_1,atel_2,atel_3,atel_4,is_push, in_enddate,IN_ENDDATE_NEW,createdby, objective_guid, send_type, caller, temp_id,listrank, release_date,release_status,sex,car_plate,modifieddate FROM (select id,customer_guid,customer_name, robot_activity_name,custlist,sysdate,tel_1,mobile,atel_1,atel_2,atel_3,atel_4,is_push, in_enddate,IN_ENDDATE_NEW,createdby, objective_guid, send_type, caller, temp_id,listrank, release_date,release_status,sex,car_plate,modifieddate,ordernumber   from robot_push_temporary where custlist in (select custlist_name from robot_standard_rule where  task_ruleid= '"+requestId+"') and Is_push = '2' and ordernumber <= "+pageNo*pageSize+") tt WHERE tt.ordernumber >  "+pageNo1*pageSize+"";
								int addHistoryRow = elite.update(addHistory, "dataSource");
								log.debug("本次推送名单至历史表记录为："+addHistoryRow);
								//下发成功数量
								count1+=addHistoryRow;
								//名单推送成功后，调用推送活动接口
								log.debug("推送任务接口请求报文：" + json1.toString());
								def reJson2 = HttpClientProxy.sendPost(url1, json1.toString(),proxyIp,proxyPort);
								JSONObject jsons1 = new JSONObject().fromObject(reJson2);
								String I_Sync_Type="ROBOT1";
								def insertSQL="DECLARE  clobValue qt_dm_ifc_log_new.Send_Info%TYPE; clobValue1 qt_dm_ifc_log_new.return_info%TYPE;  BEGIN  clobValue:='" + json1.toString() + "' ; clobValue1:='" + reJson2 + "';insert into qt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'" + requestId + "','" + I_Sync_Type + "',clobValue,clobValue1,sysdate,sysdate);   COMMIT; END;";
								elite.update(insertSQL,'dataSource');
								if(jsons1.code==0) {
									//给已经推送成功的名单打标识
									String updatesql1="update elitetask e set e.handleby_id='SELITE',e.modifieddate=sysdate  where e.objective_guid in (select objective_guid  FROM  (select objective_guid,ordernumber  from robot_push_temporary where custlist in (select custlist_name from robot_standard_rule where  task_ruleid= '"+requestId+"') and Is_push = '2' and ordernumber <= "+pageNo*pageSize+") tt WHERE tt.ordernumber >  "+pageNo1*pageSize+")";
									//log.debug("SQL222:"+updatesql1);
									elite.update(updatesql1, "dataSource");
									String updatesql2="update objective o set o.handleby_id='SELITE',o.modifieddate=sysdate where o.objective_guid in (select objective_guid  FROM  (select objective_guid,ordernumber from robot_push_temporary where custlist in (select custlist_name from robot_standard_rule where  task_ruleid= '"+requestId+"') and Is_push = '2' and ordernumber <= "+pageNo*pageSize+") tt WHERE tt.ordernumber >  "+pageNo1*pageSize+") and o.map_id in (select MAP_ID from wo3_frame_map where CATEGORY = 'SALE01')";
									//log.debug("SQL333:"+updatesql2);
									elite.update(updatesql2, "dataSource");
									//清除临时表中已经成功推送的名单
									String delTemporary = "delete from robot_push_temporary where customer_guid in ( select  customer_guid FROM  (select customer_guid,ordernumber from robot_push_temporary where custlist in (select custlist_name from robot_standard_rule where  task_ruleid= '"+requestId+"') and Is_push = '2' and ordernumber <= "+pageNo*pageSize+") tt WHERE tt.ordernumber >  "+pageNo1*pageSize+")";
									int delRow = elite.update(delTemporary, "dataSource");
									log.debug("本次推送成功清除临时表名单记录：" + delRow);
									//活动推送成功
									String sql = "update ROBOT_STANDARD_RULE set IS_FLAG = 0,MODIFIEDDATE=sysdate,STARTTIME1=STARTTIME1+1,ENDTIME1=ENDTIME1+1,STARTTIME2=STARTTIME2+1,ENDTIME2=ENDTIME2+1 where task_ruleid='" + requestId + "' and TASK_STATUS = 2";
									elite.update(sql, "dataSource");
									log.debug("推送活动成功标记状态并记录推送任务时间:"+sql);
								}else {
									//活动推送失败回滚
									String sql = "update ROBOT_STANDARD_RULE set IS_FLAG = 0,MODIFIEDDATE=sysdate,STARTTIME1=STARTTIME1+1,ENDTIME1=ENDTIME1+1,STARTTIME2=STARTTIME2+1,ENDTIME2=ENDTIME2+1 where task_ruleid='" + requestId + "' and TASK_STATUS = 2";
									elite.update(sql, "dataSource");
									log.debug("推送活动失败标记状态并记录推送任务时间:"+sql);
									//推送失败临时表数据记录状态
									String delTemporary = "update robot_push_temporary set Is_push = '3',MODIFIEDDATE=sysdate where customer_guid in ( select  customer_guid FROM  (select customer_guid,ordernumber from robot_push_temporary where custlist in (select custlist_name from robot_standard_rule where  task_ruleid= '"+requestId+"') and Is_push = '2' and ordernumber <= "+pageNo*pageSize+") tt WHERE tt.ordernumber >  "+pageNo1*pageSize+")";
									int delRow = elite.update(delTemporary, "dataSource");
									log.debug("本次推送活动失败记录：" + delRow);
								}
							}else {
								//标记状态并记录推送任务时间
								String sql = "update ROBOT_STANDARD_RULE set IS_FLAG = 1,MODIFIEDDATE=sysdate,STARTTIME1=STARTTIME1+1,ENDTIME1=ENDTIME1+1,STARTTIME2=STARTTIME2+1,ENDTIME2=ENDTIME2+1 where task_ruleid ='" + requestId + "' and TASK_STATUS = 2";
								log.debug("推送名单失败标记状态并记录推送任务时间:"+sql);
								elite.update(sql, "dataSource");
								//推送失败临时表数据记录状态
								String delTemporary = "update robot_push_temporary set Is_push = '3',MODIFIEDDATE=sysdate where customer_guid in ( select  customer_guid FROM  (select customer_guid,ordernumber from robot_push_temporary where custlist in (select custlist_name from robot_standard_rule where  task_ruleid= '"+requestId+"') and Is_push = '2' and ordernumber <= "+pageNo*pageSize+") tt WHERE tt.ordernumber >  "+pageNo1*pageSize+")";
								int delRow = elite.update(delTemporary, "dataSource");
								log.debug("本次推送名单失败记录：" + delRow);
							}
						}
					}else {
						//标记状态并记录推送任务时间
						String sql = "update ROBOT_STANDARD_RULE set IS_FLAG = 1,MODIFIEDDATE=sysdate,STARTTIME1=STARTTIME1+1,ENDTIME1=ENDTIME1+1,STARTTIME2=STARTTIME2+1,ENDTIME2=ENDTIME2+1 where task_ruleid ='" + requestId + "' and TASK_STATUS = 2";
						log.debug("未找到名单标记状态并记录推送任务时间:"+sql);
						elite.update(sql, "dataSource");
						js.put("code", 1007);
						js.put("msg", "未找到符合条件的批次");

					}
				}
				long endTime=System.currentTimeMillis();
				js.put("code", 1);
				js.put("msg", "处理完成、调用处理时长(毫秒):" + (endTime - startTime)+"共推送名单:"+count1);
				log.debug("青牛机器人首拨名单下发结束");

			}else {
				js.put("code", 1);
				js.put("msg", "处理完成、无可推送任务！");
				log.debug("青牛机器人首拨名单下发结束");

			}
		}catch (Exception e) {
	     log.debug("处理异常"+e);
		}
	}

	/**
	 * 获取推送日这天是否为节假日
	 * @param elite
	 * @param createdgroup
	 * @param inEndDate
	 * @return
	 */
	public String excuteInEndDate(EliteBean elite,String createdgroup,String inEndDate) {

		String getHolidays = "select count(1) count  from c_freedate where  createdgroup = '"+createdgroup+"' and trunc(freedate) = to_date('"+inEndDate+"','yyyy-mm-dd')";
		def results=elite.chaxun_sql(getHolidays, "dataSource");
		def queryMaps=results[0];
		def holidays = queryMaps.get("count");

		return holidays;
	}

	/**
	 * 获取保险到期日前一天
	 * @param elite
	 * @param inEndDate
	 * @return
	 */
	public String excuteBeforeDayByInEndDate(EliteBean elite,String inEndDate,int N) {

		String getBeforeDayByinEndDate = "select to_date('"+inEndDate+"','yyyy-mm-dd')-"+N+" beforeday from dual";

		def results=elite.chaxun_sql(getBeforeDayByinEndDate, "dataSource");

		def queryMaps=results[0];

		def beforeDay = queryMaps.get("beforeday");

	}

	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null
		try {
			Rev_Value = inJson.getString(getKey)
			//log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey))
				//log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
			} catch (Exception e1) {
				Rev_Value = ""
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = ""
			}
		}
		return Rev_Value
	}


	public static String getRandomString( int length){
		//定义一个字符串（A-Z，a-z，0-9）即62位；
		String str= "1234567890" ;
		//由Random生成随机数
		Random random= new Random();
		StringBuffer sb= new StringBuffer();
		//长度为几就循环几次
		for ( int i= 0 ; i<length; ++i){
			//产生0-61的数字
			int number=random.nextInt(10);
			//将产生的数字通过length次承载到sb中
			sb.append(str.charAt(number));
		}
		//将承载的字符转换成字符串
		return sb.toString();
	}

	// MD5加码。32位
	public static String MD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];

		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();

		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}

		return hexValue.toString();
	}

	// 可逆的加密算法
	public static String KL(String inStr) {
		// String s = new String(inStr);
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;
	}

	// 加密后解密
	public static String JM(String inStr) {
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String k = new String(a);
		return k;
	}
	//13位时间戳转换成date类型
	public static String timeStampDate(String time) {
		Long timeLong = Long.parseLong(time);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
		Date date;
		try {
			date = sdf.parse(sdf.format(timeLong));
			return sdf.format(date);
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";}
	}


}

